<template>
  <div class="chat-container">
    <!-- 聊天内容区域 -->
    <div class="chat-messages" ref="messagesRef">
      <div v-for="(message, index) in chatStore.messages" 
           :key="index" 
           :class="['message', message.role]">
        <div class="message-content">
          <div v-if="message.role === 'assistant'" class="markdown-body" v-html="renderMarkdown(message.content)"></div>
          <div v-else>{{ message.content }}</div>
        </div>
        <div class="message-time">{{ formatTime(message.timestamp) }}</div>
      </div>
      
      <div v-if="chatStore.loading" class="message assistant">
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="model-selector">
        <el-select v-model="selectedModel" size="large" @change="handleModelChange">
          <el-option label="OpenAI" value="openai" />
          <el-option label="通义千问" value="tongyi" />
          <el-option label="讯飞星火" value="xunfei" />
          <el-option label="文心一言" value="qianfan" />
          <el-option label="豆包" value="doubao" />
        </el-select>
      </div>
      
      <div class="input-wrapper">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入您的问题..."
          resize="none"
          @keydown.enter.exact.prevent="handleSend"
        />
        
        <el-button 
          type="primary" 
          :loading="chatStore.loading"
          @click="handleSend"
        >发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue';
import { marked } from 'marked';
import { useChatStore } from '../../stores/chat';
import { ElMessage } from 'element-plus';

const chatStore = useChatStore();
const messagesRef = ref<HTMLElement | null>(null);
const inputMessage = ref('');
const selectedModel = ref(chatStore.currentModel);

// 渲染Markdown
const renderMarkdown = (content: string) => {
  if (!content) return '';
  return marked(content);
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
};

// 处理发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim()) {
    ElMessage.warning('请输入消息内容');
    return;
  }
  
  try {
    await chatStore.sendMessage(inputMessage.value);
    inputMessage.value = '';
    await scrollToBottom();
  } catch (error: any) {
    ElMessage.error(error.message || '发送失败');
  }
};

// 处理模型切换
const handleModelChange = (model: string) => {
  chatStore.switchModel(model);
};

// 监听消息变化，自动滚动到底部
watch(() => chatStore.messages.length, scrollToBottom);

// 组件挂载时加载历史对话
onMounted(() => {
  chatStore.loadHistoryChats();
});
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 8px;
  position: relative;
}

.message.user {
  align-self: flex-end;
  background-color: var(--primary-color);
  color: white;
}

.message.assistant {
  align-self: flex-start;
  background-color: white;
  border: 1px solid var(--border-color);
}

.message-content {
  line-height: 1.6;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 5px;
  text-align: right;
}

.message.assistant .message-time {
  color: var(--text-tertiary);
}

.chat-input {
  padding: 20px;
  background-color: white;
  border-top: 1px solid var(--border-color);
}

.model-selector {
  margin-bottom: 10px;
}

.input-wrapper {
  display: flex;
  gap: 10px;
}

.input-wrapper .el-button {
  align-self: flex-end;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: var(--text-tertiary);
  border-radius: 50%;
  animation: typing 1s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-4px);
  }
}

:deep(.markdown-body) {
  background-color: transparent !important;
  color: inherit;
}

:deep(.markdown-body pre) {
  background-color: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
}

:deep(.markdown-body code) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
}
</style> 